package com.ruoyi.logistic.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;

import com.ruoyi.logistic.domain.SysUserRelation;
import com.ruoyi.logistic.domain.vo.PhoneCodeVo;
import com.ruoyi.logistic.domain.vo.PhoneLoginVo;
import com.ruoyi.logistic.domain.vo.ResetPwdVo;
import com.ruoyi.logistic.domain.vo.UserRegisterVo;
import com.ruoyi.logistic.mapper.SysUserRelationMapper;
import com.ruoyi.logistic.service.SysUserRelationService;
import com.ruoyi.logistic.service.impl.KSMSServiceImpl;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@RequestMapping("/user/login")
@RestController
@Api(tags = "登录注册")
public class SysUserLoginController {
    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private KSMSServiceImpl smsService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysUserRelationService sysUserRelationService;


    /**
     * 用户注册
     *
     * @param userRegisterVo
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public R addWantJob(@RequestBody UserRegisterVo userRegisterVo) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userRegisterVo, sysUser);
        sysUser.setUserName(sysUser.getPhone());
        if (!iSysUserService.checkUserNameUnique(sysUser)) {
            return R.fail("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getPhone()) && !iSysUserService.checkPhoneUnique(sysUser)) {
            return R.fail("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
        }
        //从redis中获取手机验证码
        String code = redisCache.getCacheObject(userRegisterVo.getPhone() + userRegisterVo.getSmsCode());
        //注册验证码 因上一步 下一步 问题 等超时后自动删除 不在手动删除
        if (userRegisterVo.getSmsCode().equals(code)) {
            redisCache.deleteObject(userRegisterVo.getPhone() + userRegisterVo.getSmsCode());
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
            //用户类型
            sysUser.setUserType("1");
            return iSysUserService.insertUser(sysUser) > 0 ? R.ok() : R.fail();
        } else {
            return R.fail("验证码错误!");
        }
    }

    /**
     * 用户登录
     *
     * @param loginBody
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginBody loginBody) {
        return loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
    }
    @ApiOperation("登录验证")
    @PostMapping("/loginVerify")
    public R loginVerify(@RequestBody LoginBody loginBody){
        return loginService.loginVerify(loginBody.getUsername(),loginBody.getPassword());
    }

    @ApiOperation("关联账户")
    @PostMapping("/relation")
    public R relation(@RequestBody SysUserRelation sysUserRelation){
        boolean isRelation = sysUserRelationService.relationAccount(sysUserRelation);
        if (isRelation){
            return R.ok("关联成功");
        }else {
            return R.fail("关联失败");
        }
    }

    @ApiOperation("显示账户信息")
    @GetMapping("getUserInfo")
    public R getUserInfo(){
        return R.ok(sysUserRelationService.findById());
    }



    /**
     * 验证码登录
     *
     * @param vo
     * @return
     */
    @ApiOperation("验证码登录")
    @PostMapping("/loginByPhone")
    public R loginByPhone(@RequestBody PhoneLoginVo vo) {
        if (StringUtils.isEmpty(vo.getPhone()) || StringUtils.isEmpty(vo.getSmsCode())) {
            return R.fail("参数缺失");
        }
        SysUser user = iSysUserService.selectUserByPhone(vo.getPhone());
        if (Objects.isNull(user)) {
            return R.fail("用户不存在,请注册后再登录！");
        }
        //从redis中获取手机验证码
        String code = redisCache.getCacheObject(vo.getPhone() + vo.getSmsCode());
        //注册验证码 因上一步 下一步 问题 等超时后自动删除 不在手动删除
        if (vo.getSmsCode().equals(code)) {
            redisCache.deleteObject(vo.getPhone() + vo.getSmsCode());
            // 生成令牌
            return loginService.loginByPhone(vo.getPhone());
        } else {
            return R.fail("验证码错误或不存在！");
        }
    }


    /**
     * 获取验证码
     *
     * @param vo
     * @return
     */
    @ApiOperation("发送验证码")
    @PostMapping("/sendSms")
    public R sendSms(@RequestBody PhoneCodeVo vo) {
        if (StringUtils.isEmpty(vo.getPhone())) {
            return R.fail("参数缺失！");
        }
        //创建对象
        JSONObject object = new JSONObject();
        //获取手机验证码并保存到redis
        String code = null;
        try {
            code = smsService.sendSmsToInternational(vo.getPhone(), vo.getAreaCode(), "zh", code);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        object.put("code", code);
        return R.ok(object);
    }

    /**
     * 重置密码
     *
     * @param vo
     * @return
     */
    @ApiOperation("重置密码")
    @PostMapping("/resetPwd")
    public R resetPwd(@RequestBody ResetPwdVo vo) {
        if (StringUtils.isEmpty(vo.getPhone()) || StringUtils.isEmpty(vo.getSmsCode()) || StringUtils.isEmpty(vo.getPassword())) {
            return R.fail("参数缺失！");
        }
        SysUser user = iSysUserService.selectUserByPhone(vo.getPhone());
        if (Objects.isNull(user)) {
            return R.fail("用户不存在！");
        }
        int i = 0;
        String code = redisCache.getCacheObject(vo.getPhone() + vo.getSmsCode());
        if (vo.getSmsCode().equals(code)) {
            i = iSysUserService.resetUserPwd(user.getUserName(), vo.getPassword());
            //删除验证码缓存
            redisCache.deleteObject(vo.getPhone() + vo.getSmsCode());
        } else {
            return R.fail("验证码错误！");
        }
        return i > 0 ? R.ok() : R.fail();
    }


}
